<?php
namespace System;

class Router {

    private $routes = Array();
    private $url;
    private $urlComponents;

    public function getRoutes() {
        return $this->routes;
    }

    public function setRoutes($routes) {
        $this->routes = $routes;
    }

    public function getUrl() {
        return $this->url;
    }

    public function splitURL() {
        $this->urlComponents = explode("/", $this->url);
        $host = array_shift($this->urlComponents);
    }

    public function setUrl($url) {
        $url = trim($url);
        $this->url = $url;
        $this->splitURL();
    }

    public function addRoute($route) {
        $this->routes[] = $route;
    }

    public function splitComponent($component) {
        $pos = strpos($component, "[");
        if (!$pos) {
            return [$component];
        } else {
            $parameter = substr($component, 0, $pos);
            $regexPattern = substr($component, $pos);
            return [$parameter, $regexPattern];
        }
    }

    public function matchComponent($urlComponent, $routeComponent) {
        $parts = $this->splitComponent($routeComponent);
        if (count($parts) == 1) {
            return (strcmp($urlComponent, $routeComponent) == 0);
        } else {
            preg_match($parts[1], $urlComponent, $matches);
            if (count($matches) > 0) {
                return (strcmp($urlComponent, $matches[0]) == 0);
            }
            else
                return false;
        }
    }

    public function match($route) {
        if (count($this->urlComponents) != count($route))
            return false;
        if (!is_array($route))
            return false;
        for ($i = 0; $i < count($route); $i++) {
            $urlComponent = $this->urlComponents[$i];
            $routeComponent = $route[$i];
            if (!$this->matchComponent($urlComponent, $routeComponent))
                return false;
        }
        return true;
    }

    public function getRoute() {
        foreach ($this->routes as $route)
            if ($this->match($route->getUrlPattern()))
                return $route;
        return false;
    }

    public function getParameter() {
        $route = $this->getRoute();
        if (!$route)
            return;
        $urlPattern = $route->getUrlPattern();
        $urlComponents = $this->urlComponents;
        
        $result = array();
        foreach ($urlComponents as $i => $urlComponent) {
            $parts = $this->splitComponent($urlPattern[$i]);
            if (count($parts) == 2) {
                $result[$parts[0]] = $urlComponent;
            }
        }
        return $result;
    }

}